package com.jeff.android.lab.module.widget.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.MutableContextWrapper;
import android.os.Build;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.jeff.android.lab.jframework.RuntimeManager;
import com.jeff.utils.LogUtil;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * WebView 池
 *
 * @author: dingfeng
 * @date: 2021/5/7
 * @since: 1.0.0
 **/
public class WebViewPool {

    private final static int max_pool_size = 3;

    private final Queue<WebView> mWebViews;

    private static volatile WebViewPool sInstance;

    public static WebViewPool getInstance() {
        if (null == sInstance) {
            synchronized (WebViewPool.class) {
                if (null == sInstance) {
                    sInstance = new WebViewPool();
                }
            }
        }
        return sInstance;
    }

    private WebViewPool() {
        mWebViews = new LinkedBlockingQueue<>(max_pool_size);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void init() {
        mWebViews.offer(create(RuntimeManager.instance().getAppContext()));
    }

    public WebView obtain(Activity activity) {
        WebView webView = mWebViews.poll();
        if (null == webView) {
            LogUtil.d("dingfeng", "WebView 池中没有缓存数据，新建一个");
            webView = create(activity);
        } else {
            LogUtil.d("dingfeng", "WebView 池中有缓存数据，设置 Context");
            MutableContextWrapper contextWrapper = (MutableContextWrapper) webView.getContext();
            contextWrapper.setBaseContext(activity);
        }
        return webView;
    }


    private WebView create(Activity activity) {
        return create((Context) activity);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private WebView create(Context context) {
        final WebView webView = new WebView(new MutableContextWrapper(context));

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setTextZoom(100);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true); // 自适应屏幕
        settings.setLoadWithOverviewMode(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE  );  //设置缓存模式

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //target 23 default false, so manual set true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setAllowContentAccess(true);
            settings.setAllowUniversalAccessFromFileURLs(true);
            settings.setAllowFileAccessFromFileURLs(true);
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }

        return webView;
    }

    public void recycle(WebView webView) {
        try {
            if (webView.getContext() instanceof MutableContextWrapper) {
                MutableContextWrapper contextWrapper = (MutableContextWrapper) webView.getContext();
                contextWrapper.setBaseContext(contextWrapper.getApplicationContext());

                webView.stopLoading();
                webView.clearHistory();
                webView.clearMatches();
                webView.clearView();
                webView.clearFocus();
                webView.clearSslPreferences();
                webView.destroyDrawingCache();
//                webView.destroy();
                if (webView.getParent() != null) {
                    ((ViewGroup) webView.getParent()).removeView(webView);
                }

                mWebViews.offer(webView);
                LogUtil.d("dingfeng", "回收 WebView，放入池中");
            }
            if (webView.getContext() instanceof Activity)
                throw new RuntimeException("Memory leaked");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
